import React, { useState } from "react";
import { Upload, Button, message, Modal, ModalProps } from "antd";
import { UploadOutlined } from "@ant-design/icons";
import { uploadExcelFile } from "../../http/request";

interface UploadModalProps extends ModalProps {
  mode?: string;
}

const UploadModal: React.FC<UploadModalProps> = (props: UploadModalProps) => {
  const { mode = "books" } = props;
  const [fileList, setFileList] = useState<any[]>([]);

  const handleChange = (info: any) => {
    let fileList = [...info.fileList];
    fileList = fileList.slice(-1); // 只保留最新上传的一个文件
    setFileList(fileList);
  };

  const handleUpload = async () => {
    if (fileList.length > 0) {
      const file = fileList[0].originFileObj;

      console.log(file,fileList,'fileList')
      try {
        const response = await uploadExcelFile(file, mode);
        message.success('更新成功');
      } catch (error) {
        message.error("Upload failed.");
      }
    } else {
      message.warning("Please select a file first.");
    }
  };

  return (
    <Modal {...props}>
      <div>
        <Upload
          accept=".xlsx, .xls"
          fileList={fileList}
          onChange={handleChange}
          beforeUpload={() => false} // 阻止自动上传
        >
          <Button icon={<UploadOutlined />}>请选择文件</Button>
        </Upload>
        <Button
          type="primary"
          onClick={handleUpload}
          disabled={fileList.length === 0}
          style={{ marginTop: 16 }}
        >
          上传
        </Button>
      </div>
    </Modal>
  );
};

export default UploadModal;
